package com.ktjiaoyu.crm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;
    @Resource
    RoleService roleService;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageIndex,
                       @RequestParam(required = false) String usrName,
                       @RequestParam(required = false) Long roleId,
                        Model model){
        //设置每页显示的条数
        Integer pageSize=3;
        //分页数据
        IPage<User> usersByPage = userService.getUsersByPage(pageIndex, pageSize, usrName, roleId);

        model.addAttribute("userPager",usersByPage);


        //查询条件回显
        model.addAttribute("usrName",usrName);
        model.addAttribute("roleId",roleId);

        return "user/list";
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @GetMapping("/add")
    public String add(Model model){
        //角色查询
        List<Role> list = roleService.findAllRoles();
        model.addAttribute("roles",list);

        return "user/add";
    }

    @PostMapping("/save")
    public String save(User user){
        int rs = userService.addUser(user);
        if(rs>0){//新增成功
            //跳转到用户列表页面
            return "redirect:/user/list";
        }else{//新增失败
            //回到新增页面
            return "redirect:/user/add";
        }
    }

    @GetMapping("/edit")
//    @RequiresPermissions("用户编辑")
    public String edit(Long usrId,Model model){
        //角色查询
        List<Role> list = roleService.findAllRoles();
        model.addAttribute("roles",list);

        User user = userService.getUser(usrId);
        model.addAttribute("user",user);

        return "user/edit";
    }

    @PostMapping("/update")
    public String update(User user){
        int rs = userService.updateUser(user);
        if(rs>0){//修改成功
            //跳转到用户列表页面
            return "redirect:/user/list";
        }else{//修改失败
            //回到修改页面
            return "redirect:/user/edit?usrId="+user.getUsrId();
        }
    }

    @GetMapping("/delete")
    @ResponseBody
    public Object delete(Long usrId){
        Map<String,Object> map=new HashMap<>();

        int rs = userService.deleteUser(usrId);
        if(rs>0){//删除成功
            map.put("delResult",true);
        }else{//删除失败
            map.put("delResult",false);
        }

        return map;
    }
}
